package cn.kgc.Adjudicative.realm;

import cn.kgc.Adjudicative.entity.DUser;
import cn.kgc.Adjudicative.entity.vo.LoginVO;
import cn.kgc.Adjudicative.service.DPermissionService;
import cn.kgc.Adjudicative.service.DRoleService;
import cn.kgc.Adjudicative.service.DUserService;
import cn.kgc.Adjudicative.token.JwtToken;
import cn.kgc.Adjudicative.utils.JwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Set;

/**
 * <p>Project:Adjudicative_document
 * <p>Package:cn.kgc.Adjudicative.realm
 * <p>ClassName:MyRealm
 * <p>Powered by sun On 2023-01-07  13:51:59
 *
 * <p>Description:Realm
 *
 * @author 孙杰
 * @version 1.0
 * @date 2023/1/7 13:51
 * @since 11
 */
@Component
public class MyRealm extends AuthorizingRealm {

    @Autowired
    private DUserService userService;

    @Autowired
    private DRoleService roleService;

    @Autowired
    private DPermissionService permissionService;

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JwtToken;
    }

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
        String username = (String) principal.iterator().next();
        Set<String> roles = roleService.getRoleByusername(username);
        Set<String> permissions = permissionService.getAllPermissionByUsername(username);
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.setRoles(roles);
        info.setStringPermissions(permissions);
        return info;
    }

    //验证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        JwtToken jwtToken = (JwtToken) token;
        String jwt = (String) jwtToken.getPrincipal();
        Claims claims = JwtUtil.parseJWT(jwt);
        String username = claims.getId();
        DUser user = userService.getUserByUsername(username);
        if (user == null){
            return null;
        }
        return new SimpleAuthenticationInfo(username,user.getPassword(),getName());
    }
}
